package org.yuzuojian.com.pojo;

import org.dom4j.DocumentException;
import org.yuzuojian.com.dom4j.Dom4jResolver;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlSessionFactory {

    private MybatisConfig mybatisConfig;
    private Dom4jResolver resolver=new Dom4jResolver();

    public SqlSession openSession() throws IOException, DocumentException, ClassNotFoundException {
        SqlSession sqlSession = new SqlSession();
        Map<Class,Mapper> mappers = new HashMap<>();
        MapperScan mapperScan = mybatisConfig.getMapperScan();
        String apackage = mapperScan.getApackage();
        String local = mapperScan.getLocal();
        /*Pattern pattern = Pattern.compile(local);
        Matcher matcher = pattern.matcher(servletPath);*/
        Enumeration<URL> resources = this.getClass().getClassLoader().getResources(local);
        while (resources.hasMoreElements()){
            URL url = resources.nextElement();
            String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
            File dir = new File(filePath);
            File[] dirfiles = dir.listFiles(new FileFilter() {
                //自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
                public boolean accept(File file) {
                    return ( file.isDirectory()) || (file.getName().endsWith(".xml"));
                }
            });
            Mapper mapper = resolver.resolverMapper(new FileInputStream(dirfiles[0]));
            mappers.put(mapper.getNamespace(),mapper);
        }

        sqlSession.setMappers(mappers);
        sqlSession.setSqlSessionFactory(this);
        return sqlSession;
    }

    public MybatisConfig getMybatisConfig() {
        return mybatisConfig;
    }

    public void setMybatisConfig(MybatisConfig mybatisConfig) {
        this.mybatisConfig = mybatisConfig;
    }
}
